package cn.nbs.user.web.servlet;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.com.hkr.servlet.BaseServlet;
import cn.nbs.user.entity.User;
import cn.nbs.user.service.UserService;


@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet{
	private UserService service = new UserService();
	public String login(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
		//1.提取用户名  密码   验证码
		String username = request.getParameter("loginname");
		String password  = request.getParameter("loginpass");
		String verifyCode = request.getParameter("verifyCode");
		
		//2.先验证验证码,获取session中的验证码
		String vcode = (String)request.getSession().getAttribute("vCode");
		if (!verifyCode.equalsIgnoreCase(vcode)) {
			request.setAttribute("msg", "验证码错误！");
			return "f:/jsps/user/login.jsp";
		}else{
			//3.验证用户名和密码
			User user = new User();
			user.setLoginpass(password);
			user.setLoginname(username);
			User u = service.login(user);
			if (u == null) {
				request.setAttribute("msg", "用户名或密码错误！");
				return  "f:/jsps/user/login.jsp";
			}else if (!u.isStatus()) {
				request.setAttribute("msg", "对不起，您还未激活！");
				return  "f:/jsps/user/login.jsp";
			}else{
				request.getSession().setAttribute("user", u);
				Cookie cookie = new Cookie("username",URLEncoder.encode(u.getLoginname(), "utf-8"));
				response.addCookie(cookie);
				return "r:/index.jsp";
			}
			//4.若成功，转发到index.jsp
		}
		
		
		
		
		
		
		
	}
}
